let records = [];

record_modal_dom.onclick = (event)=>{
    if (event.target === record_modal_dom){
        utils.display(record_modal_dom,'none')
    }
};

load_game_btn_dom.onclick = ()=>{
    console.log('load');
    utils.display(record_modal_dom,'flex');
    records = JSON.parse(localStorage.getItem('records'));
    records.sort((a,b)=>{
        return -(a.submit_at - b.submit_at);
    })
    if (records.length > 0){
        records_list_dom.innerHTML = null;
        records.forEach((item,index)=>{
            let dom = record_list_item_template_dom.cloneNode(true);
            dom.removeAttribute('id');
            utils.display(dom,'block');
            dom.onclick = load_game;
            dom.dataset.index = index.toString();
            dom.querySelector('.nickname').innerText = item.nickname;
            dom.querySelector('.submit_at').innerText = utils.Date.format(item.submit_at);
            dom.querySelector('.level').innerText = item.level;
            console.log(item);
            dom.querySelector('.wallet').innerText = item.coins;
            records_list_dom.append(dom);
        })
    }
};

const load_game = (event)=>{
    let dom = event.currentTarget;
    let record = records[dom.dataset.index] || null;
    if (record === null) return false;
    localStorage.setItem('current.nickname',record.nickname);
    localStorage.setItem('current.level',record.level);
    localStorage.setItem('current.record',JSON.stringify(record));
    localStorage.setItem('prev.score',record._score);
    window.location.href = './01_Game_Page.html';
};